package com.hangzhou.xyj.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.RecordDao;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.ui.dialog.InputDramaNameDialog;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.SelectMenuDialog;
import com.hangzhou.xyj.ui.widget.multiimageselector.utils.TimeUtils;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.Utils;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.mediaideas.videoengine.lyrics.LrcView;
import com.mediaideas.videoengine.utils.FileUtils;
import com.mediaideas.videoengine.utils.MusicUtils;

import java.lang.ref.WeakReference;

/**
 * Created by neo.duan on 2016/1/30.
 * 预览录音
 */
public class PreviewRecordActivity extends BasePlayActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, BasePlayActivity.OnMediaPlayerCompleteListener {
    private static final String TAG = "PreviewRecordActivity";
    protected ImageView mBtnPlay;
    protected SeekBar mSeekBar;
    private RecordModel mRecordModel;
    private long mDuration;//总时长

    private boolean mFromUser;//是否来自用户的拖动

    @Override
    public void initIntentData(Intent intent) {
        mRecordModel = (RecordModel) intent.getSerializableExtra(DataKey.DRAMA);
    }

    @Override
    public void initTop() {
        enableTitle(true, "录制预览");
        enableRightNav(false, "添加背景"); //暂时关闭添加背景
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                ToastUtil.show("点击了添加背景");
            }
        });
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_preview_record);
    }

    @Override
    public void initViews() {
        mLrcView = (LrcView) findViewById(R.id.lrc_view);
        mCurrentTime = (MyTextView) findViewById(R.id.current_play_time);
        mAudioDuration = (MyTextView) findViewById(R.id.audio_duration);
        mBtnPlay = (ImageView) findViewById(R.id.btn_play);
        mSeekBar = (SeekBar) findViewById(R.id.seek_bar_preview);
        mSeekBar.setOnSeekBarChangeListener(this);
    }

    @Override
    public void initDatas() {
        mHandler = new MsgHandler(this);
        mCurrentTime.setText("0:00");
        mAudioDuration.setText(TimeUtils.timeFormat(mRecordModel.getDuration(), "mm:ss"));
        mDuration = mRecordModel.getDuration();
    }

    @Override
    public void initListeners() {
        findView(R.id.rl_preview_record_restart).setOnClickListener(this);
        findView(R.id.rl_preview_record_upload).setOnClickListener(this);
        findView(R.id.rl_preview_record_save).setOnClickListener(this);
        mBtnPlay.setOnClickListener(this);
        setOnMediaPlayerCompleteListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        downloadLyric(mRecordModel.getLrcUrl());
    }

    @Override
    protected long startRefreshProgressHint() {
        if (mService == null) {
            return 500;
        }
        try {
            long position = mService.position();
            if (position >= 0 && mDuration > 0) {
                mCurrentTime.setText(MusicUtils.makeTimeString(this, position / 1000));
                int progress = (int) (1000.0f * position / mDuration);
                mSeekBar.setProgress(progress);
                if (mService.isPlaying()) {
                    Utils.showAndDismissView(mSeekBar, true);
                    Utils.showAndDismissView(mAudioDuration, true);
                    Utils.showAndDismissView(mCurrentTime, true);
                } else {
                    // blink the counter
                    int visibility = mCurrentTime.getVisibility();
                    boolean isShow = visibility == View.INVISIBLE;
                    Utils.showAndDismissView(mCurrentTime, isShow);
                    return 500;
                }
            }
            // calculate the number of milliseconds until the next full second, so
            // the counter can be updated at just the right time
            long remaining = 1000 - (position % 1000);

            // approximate how often we would need to refresh the slider to
            // move it smoothly
            int width = mSeekBar.getWidth();
            if (width == 0) width = 320;
            long smoothrefreshtime = mDuration / width;

            if (smoothrefreshtime > remaining) return remaining;
            if (smoothrefreshtime < 20) return 20;
            return smoothrefreshtime;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 500;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_play: //点击播放
                if (isMusicPlaying()) {
                    pausePlayback();
                    mBtnPlay.setImageResource(R.drawable.ic_preview_start);
                } else {
                    startPlayback(mRecordModel.getMixerFilePath());
                    mBtnPlay.setImageResource(R.drawable.ic_preview_pause);
                }
                break;
            case R.id.rl_preview_record_restart: //是否重录
                tryRecord();
                break;
            case R.id.rl_preview_record_upload: //上传服务器:其实不发布，跳转到发布页再上传
                if (mDuration <= 30000) {//小于30秒的音频 作品 不允许上传
                    ToastUtil.show("音频小于30秒，无法上传");
                    return;
                }
                if (FileUtils.isFileExists(mRecordModel.getMixerFilePath())) {
                    IntentManager.getInstance().goPublishRecordActivity(mContext, mRecordModel);
                    try {
                        mService.stop();
                        stopLrcPlay();
                        mBtnPlay.setImageResource(R.drawable.ic_preview_start);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
//                    closeActivity();
                } else {
                    ToastUtil.show("未找到录制文件");
                }
                break;
            case R.id.rl_preview_record_save: //保存到本地
                //如果没有歌曲名称，请用户输入
                if (StringUtil.isBlank(mRecordModel.getName())) {
                    showInputDramaNameDialog();
                    return;
                }
                saveRecordDrama();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        try {
            if (mService.isPlaying()) {
                mService.stop();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    /**
     * 保存录制到数据库
     */
    private void saveRecordDrama() {
        showLoadingDialog();
        findView(R.id.rl_preview_record_save).postDelayed(new Runnable() {
            @Override
            public void run() {
                RecordDao dao = new RecordDao(mContext);
                //标记为自己的id
                mRecordModel.setUserId(XYJApplication.getUserInfo().getUserId());
                dao.addDrama(mRecordModel);
                hideLoadingDialog();
                ToastUtil.show("保存成功");
                closeActivity();
            }
        }, 1000);
    }

    /**
     * 弹出输入歌曲名称对话框
     */
    private void showInputDramaNameDialog() {
        final InputDramaNameDialog dialog = new InputDramaNameDialog(mContext);
        dialog.setNegativeListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                dialog.dismiss();
                mRecordModel.setName(dialog.getDramaName());
                saveRecordDrama();
            }
        });
        dialog.show();
    }

    @Override
    protected void initBaseListeners() {
        super.initBaseListeners();
        mLlTop.setOnBackListener(new CommonTitleBarView.OnBackListener() {

            @Override
            public void onBack() {
                showGiveupRecordDlg();
            }
        });
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        mFromUser = fromUser;

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        try {
            if (mService != null && mFromUser) {
                mFromUser = false;
                mService.seek(seekBar.getProgress() * mDuration / 1000);

            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showGiveupRecordDlg();
            return true;
        }
        //继续执行父类的其他点击事件
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 应该是放弃保存：三个选项：重新录制，放弃保存，取消
     */
    protected void showGiveupRecordDlg() {
        SelectMenuDialog dialog = new SelectMenuDialog(mContext);
        dialog.setMenu(new String[]{
                "重新录制", "放弃保存"
        }, new SelectMenuDialog.SelectMenuClickListener() {
            @Override
            public void onSelectMenuClick(Dialog dialog, View item, int position) {
                switch (position) {
                    case 0: //重新录制
//                        closeActivity();
                        tryRecord();
                        break;
                    case 1: //放弃保存,直接finish
                        closeActivity();
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 重新录制
     */
    private void tryRecord() {
        TipsDialog dialog = new TipsDialog(mContext, "提示", "确定重新开始录制？",
                "确定", "取消") {
            @Override
            protected void OnClickNegativeButton() {
                this.dismiss();
            }

            @Override
            protected boolean OnClickPositiveButton() {
                if (isSingAlone()) {
                    IntentManager.getInstance().goSingAloneActivity(mContext);
                } else { //则是K歌模式
                    IntentManager.getInstance().goRecordActivity(mContext, mRecordModel);
                }
                closeActivity();//关闭本窗口
                return true;
            }
        };
        dialog.setCancel(true);
        dialog.show();
    }

    /**
     * 播放完成:初始化SeekBar和歌词
     */
//    @Override
//    public void onMediaPlayerCompletion() {
//        super.onMediaPlayerCompletion();
//        mLrcView.seekLrcToTime(0);
//        mCurrentTime.setText("0:00");
//        mBtnPlay.setImageResource(R.drawable.ic_preview_start);
//        mSeekBar.setProgress(0);
//    }

    /**
     * 判断是否是清唱: 原唱和伴奏都为空，则是清唱
     *
     * @return
     */
    protected boolean isSingAlone() {
        return StringUtil.isBlank(mRecordModel.getNativeUrl())
                && StringUtil.isBlank(mRecordModel.getAccompanyUrl());
    }

    @Override
    public void onMediaPlayerComplete() {
        try {
            mService.stop();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        mLrcView.seekLrcToTime(0);
        mCurrentTime.setText("0:00");
        mBtnPlay.setImageResource(R.drawable.ic_preview_start);
        mSeekBar.setProgress(0);
    }

    protected static class MsgHandler extends Handler {
        protected WeakReference<PreviewRecordActivity> reference;

        public MsgHandler(PreviewRecordActivity activity) {
            reference = new WeakReference<PreviewRecordActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PreviewRecordActivity activity = reference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case MSG_REFRESH_PROGRESS_POS:
                    long next = activity.startRefreshProgressHint();
                    activity.sendNextRefreshMessage(next);
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
